package com.uuj.dome.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.lang.reflect.Method;

/**
 * ClassName:ReidsConfiguration
 * PACKAGE_NAME:com.uuj.dome.config
 */
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * 自定义生成key的规则
     *
     * @return 返回秘钥生成器
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {

                // 格式化缓存key字符串
                StringBuffer buffer = new StringBuffer();
                // 追加类名
                buffer.append(o.getClass().getName());
                // 追加方法名
                buffer.append(method.getName());
                for (Object obj : objects) {
                    buffer.append(obj.toString());
                }
                return buffer.toString();
            }
        };
    }

    /**
     * 采用RedisCacheManager作为缓存管理器
     *
     * @param factory redis连接工厂
     * @return 返回缓存管理器实例对象
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        return RedisCacheManager.create(factory);
    }

}
